import 'codemirror/lib/codemirror.css'
// require active-line.js
import 'codemirror/addon/selection/active-line.js'
// styleSelectedText
import 'codemirror/addon/selection/mark-selection.js'
// hint
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/sql-hint.js'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/javascript-hint.js'
// highlightSelectionMatches
import 'codemirror/addon/scroll/annotatescrollbar.js'
import 'codemirror/addon/search/matchesonscrollbar.js'
import 'codemirror/addon/search/match-highlighter.js'
import 'codemirror/addon/selection/active-line'
// keyMap
import 'codemirror/mode/clike/clike.js'
import 'codemirror/mode/sql/sql.js'
import 'codemirror/addon/edit/matchbrackets.js'
import 'codemirror/addon/comment/comment.js'
import 'codemirror/addon/dialog/dialog.js'
import 'codemirror/addon/dialog/dialog.css'
import 'codemirror/addon/search/searchcursor.js'
import 'codemirror/addon/search/search.js'
import 'codemirror/keymap/sublime.js'
// foldGutter
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/brace-fold.js'
import 'codemirror/addon/fold/comment-fold.js'
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/indent-fold.js'
import 'codemirror/addon/fold/markdown-fold.js'
import 'codemirror/addon/fold/xml-fold.js'
// 编辑的主题文件
import 'codemirror/theme/monokai.css'
import 'codemirror/theme/base16-light.css'
import modal from '@/plugins/modal'
import { getDataBase } from '@/api/tool/dbase'

let database = []
let tables = {}
let columns = {}

export function getDatabaseInfo(dbKey) {
  getDataBase(dbKey).then(response => {
    if (response.code === 200) {
      database = response.param.dbNames
      tables = response.param.tables
      columns = response.param.columns
    }
    modal.notifySuccess('数据表信息加载完成')
    database = database || []
  })
}

export function searchTableName(curLine, ch) {
  const line = curLine.substring(0, ch)
  let str = ''
  for (let i = ch - 1; i > 0; i--) {
    if (line.charAt(i) !== ' ') {
      str = line.charAt(i) + str
    } else {
      return str
    }
  }
  return str
}

export function searchTable(dbKey, keyword) {
  let list = []
  if (tables[dbKey]) {
    for (let i = 0, len = tables[dbKey].length; i < len; i++) {
      const table = tables[dbKey][i]
      if (keyword == null || (table.tableName.indexOf(keyword) > -1)) {
        list.push(table.tableName)
      }
    }
    list = list.sort()
  }
  return list
}

export function searchColumn(tableName, keyword) {
  let list = []
  if (columns[tableName]) {
    for (let i = 0, len = columns[tableName].length; i < len; i++) {
      const column = columns[tableName][i]
      if (keyword == null || (column.columnName.indexOf(keyword) > -1)) {
        list.push(column.columnName)
      }
    }
    list = list.sort()
  }
  return list
}
